<template>
  <el-card>
    <h2>SNMP信息管理</h2>

    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="设备IP">
        <el-input v-model="queryForm.ip" placeholder="请输入设备IP" clearable></el-input>
      </el-form-item>
      <el-form-item label="设备类型">
        <el-select v-model="queryForm.type" placeholder="请选择设备类型" clearable>
          <el-option label="服务器" :value="1"></el-option>
          <el-option label="交换机" :value="2"></el-option>
          <el-option label="PDU" :value="3"></el-option>
          <el-option label="播控器" :value="4"></el-option>
          <el-option label="LED" :value="5"></el-option>
          <el-option label="NTP" :value="9"></el-option>
          <el-option label="WiFi" :value="51"></el-option>
          <el-option label="车地无线" :value="52"></el-option>
          <el-option label="车地无线转储" :value="53"></el-option>
          <el-option label="编播设备" :value="54"></el-option>
          <el-option label="网络设备" :value="99"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态">
        <el-select v-model="queryForm.enable" placeholder="请选择状态" clearable>
          <el-option label="启用" :value="1"></el-option>
          <el-option label="禁用" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="success" @click="openDialog">新增</el-button>
        <el-button type="warning" @click="openSyncDialog" :loading="syncLoading">数据同步</el-button>
        <el-button type="info" @click="openCompareDialog" :loading="compareLoading">同步状态</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="ip" label="设备IP"></el-table-column>
      <el-table-column prop="community" label="团体名"></el-table-column>
      <el-table-column prop="version" label="SNMP版本">
        <template #default="scope">
          {{ scope.row.version === null || scope.row.version === undefined ? '-' : 
             scope.row.version === 0 ? 'v1' :
             scope.row.version === 1 ? 'v2c' : 'v3' }}
        </template>
      </el-table-column>
      <el-table-column prop="model" label="型号"></el-table-column>
      <el-table-column prop="type" label="设备类型">
        <template #default="scope">
          {{ getDeviceType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="enable" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.enable ? 'success' : 'danger'">
            {{ scope.row.enable ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button :type="scope.row.enable ? 'danger' : 'success'" size="mini" @click="handleToggleEnable(scope.row)">
            {{ scope.row.enable ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加对话框 -->
    <SnmpFormDialog 
      ref="snmpFormDialog" 
      :models="models"
      :visible.sync="dialogVisible"
      :form-data="formData"
      @success="handleSuccess"
    />

    <!-- 数据同步对话框 -->
    <el-dialog title="数据同步" :visible.sync="syncDialogVisible" width="500px">
      <el-form :model="syncForm" label-width="120px">
        <el-form-item label="同步设备信息">
          <el-switch v-model="syncForm.sync_devices"></el-switch>
        </el-form-item>
        <el-form-item label="同步服务器信息">
          <el-switch v-model="syncForm.sync_servers"></el-switch>
        </el-form-item>
        <el-form-item label="同步PDU信息">
          <el-switch v-model="syncForm.sync_pdus"></el-switch>
        </el-form-item>
        <el-form-item label="同步交换机信息">
          <el-switch v-model="syncForm.sync_switches"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="syncDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSync" :loading="syncLoading">开始同步</el-button>
      </div>
    </el-dialog>

    <!-- 同步状态比对对话框 -->
    <el-dialog title="设备同步状态比对" :visible.sync="compareDialogVisible" width="80%" top="5vh">
      <div v-if="compareData">
        <!-- 汇总信息 -->
        <el-card class="summary-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>汇总信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-number">{{ compareData.summary.total_devices }}</div>
                <div class="summary-label">总设备数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-number success">{{ compareData.summary.synced_devices }}</div>
                <div class="summary-label">已同步</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-number warning">{{ compareData.summary.unsynced_devices }}</div>
                <div class="summary-label">未同步</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-number info">{{ compareData.summary.excluded_devices }}</div>
                <div class="summary-label">已排除</div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 详细比对结果 -->
        <el-tabs v-model="activeTab" class="compare-tabs">
          <!-- 设备信息 -->
          <el-tab-pane label="播控设备" name="devices">
            <div class="tab-header">
              <span>总数: {{ compareData.device_comparison.total_count }}</span>
              <span class="success">已同步: {{ compareData.device_comparison.synced_count }}</span>
              <span class="warning">未同步: {{ compareData.device_comparison.unsynced_count }}</span>
              <span class="info">排除车载: {{ compareData.device_comparison.excluded_count }}</span>
            </div>
            <el-table :data="compareData.device_comparison.unsynced_devices" style="width: 100%" max-height="300">
              <el-table-column prop="device_id" label="设备ID" width="120"></el-table-column>
              <el-table-column prop="device_name" label="设备名称"></el-table-column>
              <el-table-column prop="ip" label="IP地址" width="120"></el-table-column>
              <el-table-column prop="type" label="类型" width="80">
                <template #default="scope">
                  {{ scope.row.type === 1 ? 'LCD' : scope.row.type === 2 ? 'LED' : '其他' }}
                </template>
              </el-table-column>
              <el-table-column prop="district" label="区域" width="80">
                <template #default="scope">
                  {{ getDistrictName(scope.row.district) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 服务器信息 -->
          <el-tab-pane label="服务器" name="servers">
            <div class="tab-header">
              <span>总数: {{ compareData.server_comparison.total_count }}</span>
              <span class="success">已同步: {{ compareData.server_comparison.synced_count }}</span>
              <span class="warning">未同步: {{ compareData.server_comparison.unsynced_count }}</span>
            </div>
            <el-table :data="compareData.server_comparison.unsynced_servers" style="width: 100%" max-height="300">
              <el-table-column prop="id" label="服务器ID" width="120"></el-table-column>
              <el-table-column prop="name" label="服务器名称"></el-table-column>
              <el-table-column prop="ip" label="IP地址" width="120"></el-table-column>
              <el-table-column prop="station_name" label="车站名称"></el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- PDU信息 -->
          <el-tab-pane label="PDU设备" name="pdus">
            <div class="tab-header">
              <span>总数: {{ compareData.pdu_comparison.total_count }}</span>
              <span class="success">已同步: {{ compareData.pdu_comparison.synced_count }}</span>
              <span class="warning">未同步: {{ compareData.pdu_comparison.unsynced_count }}</span>
            </div>
            <el-table :data="compareData.pdu_comparison.unsynced_pdus" style="width: 100%" max-height="300">
              <el-table-column prop="id" label="PDU ID" width="100"></el-table-column>
              <el-table-column prop="number" label="编号" width="120"></el-table-column>
              <el-table-column prop="name" label="PDU名称"></el-table-column>
              <el-table-column prop="ip" label="IP地址" width="120"></el-table-column>
              <el-table-column prop="station_name" label="车站名称"></el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 交换机信息 -->
          <el-tab-pane label="交换机" name="switches">
            <div class="tab-header">
              <span>总数: {{ compareData.switch_comparison.total_count }}</span>
              <span class="success">已同步: {{ compareData.switch_comparison.synced_count }}</span>
              <span class="warning">未同步: {{ compareData.switch_comparison.unsynced_count }}</span>
            </div>
            <el-table :data="compareData.switch_comparison.unsynced_switches" style="width: 100%" max-height="300">
              <el-table-column prop="id" label="交换机ID" width="120"></el-table-column>
              <el-table-column prop="name" label="交换机名称"></el-table-column>
              <el-table-column prop="ip" label="IP地址" width="120"></el-table-column>
              <el-table-column prop="station_name" label="车站名称"></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="compareDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="refreshCompare" :loading="compareLoading">刷新</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import SnmpFormDialog from './SnmpFormDialog.vue'
import axios from 'axios'

export default {
  components: {
    SnmpFormDialog
  },
  data() {
    return {
      queryForm: {
        ip: '',
        type: '',
        enable: '',
        page: 1,
        pageSize: 10
      },
      tableData: [],
      total: 0,
      models: [],
      dialogVisible: false,
      formData: {},
      syncDialogVisible: false,
      syncLoading: false,
      syncForm: {
        sync_devices: true,
        sync_servers: true,
        sync_pdus: true,
        sync_switches: true
      },
      compareDialogVisible: false,
      compareLoading: false,
      compareData: null,
      activeTab: 'devices'
    }
  },
  methods: {
    getDeviceType(type) {
      const typeMap = {
        1: '服务器',
        2: '交换机',
        3: 'PDU',
        4: '播控器',
        9: 'NTP',
        10: '网络设备'
      }
      return typeMap[type] || '未知'
    },
    fetchModelList() {
      axios.get('/pidscloud/model')
        .then(response => {
          this.models = response.data.data;
        })
        .catch(error => {
          console.error('获取型号列表失败:', error);
        });
    },
    onQuery() {
      this.queryForm.page = 1
      this.getSnmpInfoList()
    },
    resetQuery() {
      this.queryForm = {
        ip: '',
        type: '',
        enable: '',
        page: 1,
        pageSize: 10
      };
      this.getSnmpInfoList();
    },
    getSnmpInfoList() {
      axios.get('/pidscloud/snmp/list', {
        params: this.queryForm
      }).then(response => {
        const { list, total, page, pageSize } = response.data.data
        this.tableData = list
        this.total = total
        this.queryForm.page = page
        this.queryForm.pageSize = pageSize
      })
      .catch(error => {
        console.error('获取SNMP信息列表失败:', error);
      });
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.getSnmpInfoList()
    },
    handleCurrentChange(val) {
      this.queryForm.page = val
      this.getSnmpInfoList()
    },
    handleSuccess() {
      this.dialogVisible = false
      this.getSnmpInfoList()
    },
    openDialog() {
      this.formData = {}
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确定删除该SNMP信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/pidscloud/snmp/delete/${row.id}`)
          .then(() => {
            this.$message.success('删除成功');
            this.getSnmpInfoList();
          })
          .catch(error => {
            console.error('删除失败:', error);
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleToggleEnable(row) {
      const newEnable = row.enable ? 0 : 1;
      axios.put('/pidscloud/snmp/update', {
        id: row.id,
        enable: newEnable
      }).then(() => {
        this.$message.success(newEnable ? '启用成功' : '禁用成功');
        this.getSnmpInfoList();
      }).catch(error => {
        console.error('操作失败:', error);
      });
    },
    handleEdit(row) {
      this.formData = { ...row }
      this.dialogVisible = true
    },
    openSyncDialog() {
      this.syncDialogVisible = true
    },
    handleSync() {
      this.syncLoading = true
      axios.post('/pidscloud/sync/snmp', this.syncForm)
        .then(response => {
          const data = response.data.data
          this.$message.success(
            `同步完成！总计: ${data.total_count}, 成功: ${data.success_count}, 失败: ${data.failed_count}`
          )
          this.syncDialogVisible = false
          this.getSnmpInfoList() // 刷新列表
        })
        .catch(error => {
          console.error('同步失败:', error)
          this.$message.error('同步失败: ' + (error.response?.data?.message || error.message))
        })
        .finally(() => {
          this.syncLoading = false
        })
    },
    openCompareDialog() {
      this.compareDialogVisible = true
      this.loadCompareData()
    },
    loadCompareData() {
      this.compareLoading = true
      axios.get('/pidscloud/sync/compare')
        .then(response => {
          this.compareData = response.data.data
        })
        .catch(error => {
          console.error('获取比对数据失败:', error)
          this.$message.error('获取比对数据失败: ' + (error.response?.data?.message || error.message))
        })
        .finally(() => {
          this.compareLoading = false
        })
    },
    refreshCompare() {
      this.loadCompareData()
    },
    getDistrictName(district) {
      const districtMap = {
        1: '上行',
        2: '下行', 
        3: '站厅',
        4: '车载'
      }
      return district ? districtMap[district] || '未知' : '-'
    }
  },
  mounted() {
    this.getSnmpInfoList();
    this.fetchModelList();
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.summary-card {
  margin-bottom: 20px;
}

.summary-item {
  text-align: center;
  padding: 20px;
}

.summary-number {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.summary-number.success {
  color: #67c23a;
}

.summary-number.warning {
  color: #e6a23c;
}

.summary-number.info {
  color: #909399;
}

.summary-label {
  font-size: 14px;
  color: #606266;
}

.compare-tabs {
  margin-top: 20px;
}

.tab-header {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.tab-header span {
  margin-right: 20px;
  font-weight: bold;
}

.tab-header .success {
  color: #67c23a;
}

.tab-header .warning {
  color: #e6a23c;
}

.tab-header .info {
  color: #909399;
}
</style>